<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>陪玩推荐系统 - 交互式测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 350px 1fr;
            gap: 20px;
        }

        .panel {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            padding: 25px;
        }

        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
            grid-column: 1 / -1;
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }

        .control-panel {
            height: fit-content;
            position: sticky;
            top: 20px;
        }

        .control-group {
            margin-bottom: 25px;
        }

        .control-group label {
            display: block;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            font-size: 14px;
        }

        .control-group input[type="range"] {
            width: 100%;
            height: 6px;
            border-radius: 3px;
            background: #ddd;
            outline: none;
            -webkit-appearance: none;
        }

        .control-group input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: #667eea;
            cursor: pointer;
        }

        .control-group input[type="range"]::-moz-range-thumb {
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: #667eea;
            cursor: pointer;
        }

        .range-value {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 13px;
            font-weight: bold;
            margin-left: 10px;
        }

        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            background: #f5f5f5;
            padding: 6px 12px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 13px;
        }

        .checkbox-item:hover {
            background: #e0e0e0;
        }

        .checkbox-item input[type="checkbox"] {
            margin-right: 5px;
        }

        .checkbox-item input[type="checkbox"]:checked + span {
            color: #667eea;
            font-weight: bold;
        }

        select {
            width: 100%;
            padding: 10px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            background: white;
            cursor: pointer;
        }

        select:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn-recommend {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 20px;
        }

        .btn-recommend:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }

        .btn-recommend:active {
            transform: translateY(0);
        }

        .results-panel {
            min-height: 600px;
        }

        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e0e0e0;
        }

        .results-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }

        .results-count {
            background: #667eea;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 14px;
        }

        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #999;
            font-size: 16px;
        }

        .loading::after {
            content: '...';
            animation: dots 1.5s steps(4, end) infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60%, 100% { content: '...'; }
        }

        .results-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
        }

        .player-card {
            background: white;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 18px;
            transition: all 0.3s;
            position: relative;
        }

        .player-card:hover {
            border-color: #667eea;
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.2);
            transform: translateY(-3px);
        }

        .player-card.new {
            border-color: #ff6b6b;
            background: linear-gradient(135deg, #fff5f5 0%, #ffffff 100%);
        }

        .player-card.new::before {
            content: "🆕";
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 20px;
        }

        .rank-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 14px;
        }

        .player-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            margin-top: 25px;
        }

        .player-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 20px;
            margin-right: 12px;
        }

        .player-info {
            flex: 1;
        }

        .player-name {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-bottom: 5px;
        }

        .player-status {
            font-size: 12px;
        }

        .status-online {
            color: #52c41a;
            font-weight: bold;
        }

        .status-offline {
            color: #999;
        }

        .player-details {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #eee;
        }

        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 13px;
        }

        .detail-label {
            color: #999;
        }

        .detail-value {
            color: #333;
            font-weight: bold;
        }

        .games {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
            margin-top: 3px;
        }

        .game-tag {
            background: #e8f4f8;
            color: #1890ff;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 11px;
        }

        .price {
            color: #ff6b6b;
            font-size: 18px;
            font-weight: bold;
        }

        .rating {
            color: #faad14;
        }

        .score-section {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 8px;
            margin-top: 10px;
        }

        .score-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 5px;
            font-size: 12px;
        }

        .score-row:last-child {
            margin-bottom: 0;
        }

        .score-label {
            color: #666;
        }

        .score-bar-container {
            flex: 1;
            height: 6px;
            background: #e0e0e0;
            border-radius: 3px;
            margin: 0 10px;
            overflow: hidden;
        }

        .score-bar {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
            border-radius: 3px;
            transition: width 0.3s;
        }

        .score-value {
            color: #667eea;
            font-weight: bold;
            min-width: 45px;
            text-align: right;
        }

        .stats {
            background: #f0f9ff;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
        }

        .stat-item {
            text-align: center;
        }

        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        .no-results {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .no-results-icon {
            font-size: 60px;
            margin-bottom: 20px;
        }

        .info-box {
            background: #e6f7ff;
            border-left: 4px solid #1890ff;
            padding: 12px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 13px;
            color: #333;
        }

        .user-profile {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .user-profile h3 {
            font-size: 16px;
            color: #333;
            margin-bottom: 12px;
        }

        .profile-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 13px;
        }

        .profile-label {
            color: #666;
        }

        .profile-value {
            color: #333;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎮 陪玩推荐系统 - 交互式测试平台</h1>

        <!-- 控制面板 -->
        <div class="panel control-panel">
            <h2 style="margin-bottom: 20px; font-size: 18px; color: #333;">📊 用户参数设置</h2>

            <div class="user-profile">
                <h3>👤 当前用户画像</h3>
                <div class="profile-item">
                    <span class="profile-label">用户ID:</span>
                    <span class="profile-value" id="currentUserId">-</span>
                </div>
                <div class="profile-item">
                    <span class="profile-label">历史订单:</span>
                    <span class="profile-value" id="currentOrderCount">-</span>
                </div>
                <div class="profile-item">
                    <span class="profile-label">平均消费:</span>
                    <span class="profile-value" id="currentAvgPrice">-</span>
                </div>
            </div>

            <div class="info-box">
                💡 调节参数后点击"获取推荐"查看效果
            </div>

            <div class="control-group">
                <label>
                    📦 历史订单数：<span class="range-value" id="orderCountValue">15</span>
                </label>
                <input type="range" id="orderCount" min="0" max="100" value="15" step="1">
                <div style="display: flex; justify-content: space-between; font-size: 11px; color: #999; margin-top: 5px;">
                    <span>新用户 0</span>
                    <span>100 老用户</span>
                </div>
            </div>

            <div class="control-group">
                <label>
                    💰 平均消费价格：<span class="range-value" id="avgPriceValue">40</span> 元/小时
                </label>
                <input type="range" id="avgPrice" min="20" max="80" value="40" step="5">
                <div style="display: flex; justify-content: space-between; font-size: 11px; color: #999; margin-top: 5px;">
                    <span>低消费 20</span>
                    <span>80 高消费</span>
                </div>
            </div>

            <div class="control-group">
                <label>🎮 喜欢的游戏（多选）：</label>
                <div class="checkbox-group">
                    <label class="checkbox-item">
                        <input type="checkbox" name="game" value="王者荣耀" checked>
                        <span>王者荣耀</span>
                    </label>
                    <label class="checkbox-item">
                        <input type="checkbox" name="game" value="LOL">
                        <span>LOL</span>
                    </label>
                    <label class="checkbox-item">
                        <input type="checkbox" name="game" value="和平精英" checked>
                        <span>和平精英</span>
                    </label>
                    <label class="checkbox-item">
                        <input type="checkbox" name="game" value="原神">
                        <span>原神</span>
                    </label>
                    <label class="checkbox-item">
                        <input type="checkbox" name="game" value="CSGO">
                        <span>CSGO</span>
                    </label>
                    <label class="checkbox-item">
                        <input type="checkbox" name="game" value="永劫无间">
                        <span>永劫无间</span>
                    </label>
                </div>
            </div>

            <div class="control-group">
                <label>🎤 偏好声线：</label>
                <select id="voiceType">
                    <option value="">不限</option>
                    <option value="御姐" selected>御姐</option>
                    <option value="少女">少女</option>
                    <option value="萝莉">萝莉</option>
                    <option value="大叔">大叔</option>
                    <option value="正太">正太</option>
                </select>
            </div>

            <div class="control-group">
                <label>
                    🔢 推荐数量：<span class="range-value" id="limitValue">20</span>
                </label>
                <input type="range" id="limit" min="10" max="50" value="20" step="5">
            </div>

            <div class="control-group">
                <label>🎯 推荐场景：</label>
                <select id="scenario">
                    <option value="home">首页推荐</option>
                    <option value="game">游戏分类</option>
                </select>
            </div>

            <button class="btn-recommend" onclick="getRecommendations()">
                🚀 获取推荐
            </button>
        </div>

        <!-- 结果面板 -->
        <div class="panel results-panel">
            <div class="results-header">
                <div class="results-title">推荐结果</div>
                <div class="results-count" id="resultsCount">等待推荐...</div>
            </div>

            <div class="stats" id="statsSection" style="display: none;">
                <div class="stats-grid">
                    <div class="stat-item">
                        <div class="stat-value" id="statAvgScore">-</div>
                        <div class="stat-label">平均得分</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="statOnline">-</div>
                        <div class="stat-label">在线人数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="statAvgPrice">-</div>
                        <div class="stat-label">平均价格</div>
                    </div>
                </div>
            </div>

            <div id="resultsContainer">
                <div class="loading" id="loadingMsg" style="display: none;">正在加载推荐</div>
                <div class="no-results">
                    <div class="no-results-icon">🎯</div>
                    <div>请调节左侧参数，然后点击"获取推荐"查看效果</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 范围滑块实时更新
        document.getElementById('orderCount').addEventListener('input', function(e) {
            document.getElementById('orderCountValue').textContent = e.target.value;
        });

        document.getElementById('avgPrice').addEventListener('input', function(e) {
            document.getElementById('avgPriceValue').textContent = e.target.value;
        });

        document.getElementById('limit').addEventListener('input', function(e) {
            document.getElementById('limitValue').textContent = e.target.value;
        });

        // 获取选中的游戏
        function getSelectedGames() {
            const checkboxes = document.querySelectorAll('input[name="game"]:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 获取推荐
        async function getRecommendations() {
            const orderCount = parseInt(document.getElementById('orderCount').value);
            const avgPrice = parseInt(document.getElementById('avgPrice').value);
            const games = getSelectedGames();
            const voiceType = document.getElementById('voiceType').value;
            const limit = parseInt(document.getElementById('limit').value);
            const scenario = document.getElementById('scenario').value;

            // 验证
            if (games.length === 0) {
                alert('请至少选择一个喜欢的游戏！');
                return;
            }

            // 显示加载
            document.getElementById('resultsContainer').innerHTML = 
                '<div class="loading">正在加载推荐...</div>';
            document.getElementById('resultsCount').textContent = '加载中...';
            document.getElementById('statsSection').style.display = 'none';

            // 构造用户数据
            const userData = {
                user_id: 9999,
                order_count: orderCount,
                avg_price: avgPrice,
                favorite_games: games,
                preferred_voice: voiceType,
                limit: limit
            };

            // 更新用户画像显示
            document.getElementById('currentUserId').textContent = '9999 (测试用户)';
            document.getElementById('currentOrderCount').textContent = `${orderCount} 单`;
            document.getElementById('currentAvgPrice').textContent = `¥${avgPrice}/小时`;

            try {
                // 调用Python推荐引擎
                const response = await fetch('http://localhost:5000/api/recommend/home', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(userData)
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                
                if (data.success) {
                    displayResults(data.data.recommendations.slice(0, limit));
                } else {
                    throw new Error(data.message || '推荐失败');
                }
            } catch (error) {
                console.error('Error:', error);
                // 使用模拟数据展示
                await getRecommendationsOffline(userData);
            }
        }

        // 离线模拟推荐（用于测试）
        async function getRecommendationsOffline(userData) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 500));

            // 模拟推荐结果
            const mockResults = generateMockResults(userData);
            displayResults(mockResults);
        }

        // 生成模拟数据
        function generateMockResults(userData) {
            const games = ['王者荣耀', 'LOL', '和平精英', '原神', 'CSGO', '永劫无间'];
            const voices = ['御姐', '少女', '萝莉', '大叔', '正太'];
            const results = [];
            const limit = userData.limit || 20;

            for (let i = 1; i <= limit; i++) {
                const playerGames = [];
                const numGames = Math.floor(Math.random() * 3) + 1;
                for (let j = 0; j < numGames; j++) {
                    const game = games[Math.floor(Math.random() * games.length)];
                    if (!playerGames.includes(game)) {
                        playerGames.push(game);
                    }
                }

                // 根据用户订单数调整得分
                const baseScore = 0.5 + Math.random() * 0.3;
                const orderBonus = userData.order_count > 0 ? 0.1 : 0;
                const finalScore = Math.min(baseScore + orderBonus, 0.95);

                // 根据用户偏好调整价格匹配
                const priceDiff = Math.abs(userData.avg_price - (20 + Math.random() * 60));
                const priceScore = Math.max(0.5, 1 - priceDiff / 100);

                const result = {
                    player_id: 1000 + i,
                    nickname: i <= 5 ? `明星陪玩${i}` : `陪玩师${i}号`,
                    games: playerGames,
                    voice_type: voices[Math.floor(Math.random() * voices.length)],
                    price: Math.floor(20 + Math.random() * 60 / 5) * 5,
                    rating: (4.0 + Math.random() * 1.0).toFixed(1),
                    online: Math.random() > 0.25,
                    is_new: i > limit - 3,
                    total_orders: Math.floor(Math.random() * 1000),
                    final_score: finalScore,
                    ai_match_score: (0.5 + Math.random() * 0.3).toFixed(3),
                    price_match_score: priceScore.toFixed(3),
                    response_time: Math.floor(Math.random() * 15) + 1
                };

                results.push(result);
            }

            // 按得分排序
            return results.sort((a, b) => b.final_score - a.final_score);
        }

        // 显示结果
        function displayResults(results) {
            if (!results || results.length === 0) {
                document.getElementById('resultsContainer').innerHTML = `
                    <div class="no-results">
                        <div class="no-results-icon">😔</div>
                        <div>暂无符合条件的推荐结果</div>
                    </div>
                `;
                document.getElementById('resultsCount').textContent = '0 个结果';
                return;
            }

            // 更新统计
            const avgScore = (results.reduce((sum, r) => sum + (r.final_score || 0), 0) / results.length * 100).toFixed(1);
            const onlineCount = results.filter(r => r.online).length;
            const avgPrice = Math.round(results.reduce((sum, r) => sum + r.price, 0) / results.length);

            document.getElementById('statAvgScore').textContent = avgScore + '%';
            document.getElementById('statOnline').textContent = onlineCount;
            document.getElementById('statAvgPrice').textContent = '¥' + avgPrice;
            document.getElementById('statsSection').style.display = 'block';

            // 显示结果数量
            document.getElementById('resultsCount').textContent = `共 ${results.length} 个推荐`;

            // 渲染卡片
            const html = results.map((player, index) => `
                <div class="player-card ${player.is_new ? 'new' : ''}">
                    <div class="rank-badge">${index + 1}</div>
                    <div class="player-header">
                        <div class="player-avatar">${player.nickname ? player.nickname.charAt(0) : '?'}</div>
                        <div class="player-info">
                            <div class="player-name">${player.nickname || '未知'}</div>
                            <div class="player-status ${player.online ? 'status-online' : 'status-offline'}">
                                ${player.online ? '🟢 在线' : '🔴 离线'}
                            </div>
                        </div>
                    </div>
                    <div class="player-details">
                        <div class="detail-row">
                            <span class="detail-label">游戏:</span>
                            <div class="games">
                                ${(player.games || []).map(g => `<span class="game-tag">${g}</span>`).join('')}
                            </div>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">声线:</span>
                            <span class="detail-value">${player.voice_type || '未知'}</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">价格:</span>
                            <span class="detail-value price">¥${player.price}/小时</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">评分:</span>
                            <span class="detail-value rating">${player.rating} ⭐</span>
                        </div>
                        <div class="detail-row">
                            <span class="detail-label">历史订单:</span>
                            <span class="detail-value">${player.total_orders || 0} 单</span>
                        </div>
                    </div>
                    ${player.final_score || player.ai_match_score ? `
                    <div class="score-section">
                        ${player.final_score ? `
                        <div class="score-row">
                            <span class="score-label">综合得分</span>
                            <div class="score-bar-container">
                                <div class="score-bar" style="width: ${player.final_score * 100}%"></div>
                            </div>
                            <span class="score-value">${(player.final_score * 100).toFixed(1)}%</span>
                        </div>
                        ` : ''}
                        ${player.ai_match_score ? `
                        <div class="score-row">
                            <span class="score-label">AI匹配</span>
                            <div class="score-bar-container">
                                <div class="score-bar" style="width: ${player.ai_match_score * 100}%"></div>
                            </div>
                            <span class="score-value">${(player.ai_match_score * 100).toFixed(1)}%</span>
                        </div>
                        ` : ''}
                        ${player.price_match_score ? `
                        <div class="score-row">
                            <span class="score-label">价格匹配</span>
                            <div class="score-bar-container">
                                <div class="score-bar" style="width: ${player.price_match_score * 100}%"></div>
                            </div>
                            <span class="score-value">${(player.price_match_score * 100).toFixed(1)}%</span>
                        </div>
                        ` : ''}
                    </div>
                    ` : ''}
                </div>
            `).join('');

            document.getElementById('resultsContainer').innerHTML = `
                <div class="results-grid">
                    ${html}
                </div>
            `;
        }

        // 页面加载时设置默认值
        window.addEventListener('load', function() {
            // 可以在这里加载一次默认推荐
            console.log('页面已加载，准备接收推荐请求');
        });
    </script>
</body>
</html>

